package 链表;

import java.lang.management.BufferPoolMXBean;

class ListNode {
    int val;
    ListNode next = null;
    public ListNode(int val) {
      this.val = val;
    }
}

public class Solution1 {
    public ListNode Merge (ListNode pHead1, ListNode pHead2) {
        ListNode retHead = null;
        ListNode tail = null;
        ListNode cur1 = pHead1;
        ListNode cur2 = pHead2;
        if(pHead1 == null && pHead2 == null) {
            return null;
        }
        if(pHead1 == null) {
            return pHead2;
        }
        if(pHead2 == null) {
            return pHead1;
        }
        while(cur1 != null && cur2 != null) {
            if(cur1.val > cur2.val) {
                if(retHead == null) {
                    retHead = new ListNode(cur2.val);
                    tail = retHead;
                }else {
                    tail.next = new ListNode(cur2.val);
                    tail = tail.next;
                }
                cur2 = cur2.next;
            }else {
                if(retHead == null) {
                    retHead = new ListNode(cur1.val);
                    tail = retHead;
                }else {
                    tail.next = new ListNode(cur1.val);
                    tail = tail.next;
                }
                cur1 = cur1.next;
            }
        }
        if(cur1 == null) {
            tail.next = cur2;
        }else {
            tail.next = cur1;
        }
        return retHead;
    }
}
